<?php
include("session.php");
include("config.php");
include("isublist_block.php");
if (!validate(1, "maintime.php", $db, "login.php"))
   exit();
?>

<html>

<head>
   <title>Easy Time Tracker</title>
   <script src="/datepicker/easy.datepicker.js" type="text/javascript" charset="utf-8"></script>
   <link rel="stylesheet" href="/datepicker/vanilla.datepicker.css" type="text/css" media="screen" />
   <link rel="stylesheet" href="/timetracker.css" type="text/css" media="screen" />
   <script src="/datepicker/js-timepicker.js"></script>
   <link rel="stylesheet" href="/datepicker/js-timepicker.css">
   <script type="text/javascript">
      <?php
      //Get last customer,project and task to client via js
      $lastcustomer = 0;
      if (isset($_SESSION['lastcustomer']))
         $lastcustomer = $_SESSION['lastcustomer'];

      $lastProject = 0;
      if (isset($_SESSION['lastproject']))
         $lastProject = $_SESSION['lastproject'];

      $lastTask = 0;
      if (isset($_SESSION['lasttask']))
         $lastTask = $_SESSION['lasttask'];
      ?>
      if (sessionStorage.selectCustomer == null)
         sessionStorage.selectedCustomer = <?php echo ($lastcustomer) ?>;
      //Indexed Objects would have been good here, but session-API does not allow objects...
      //.. so we have to use string indext for everything... ;_(
      var pid = 0;
      if (sessionStorage.getItem("selectedProject" + sessionStorage.selectedCustomer) == null) {
         pid = <?php echo ($lastProject); ?>;
         sessionStorage.setItem("selectedProject" + sessionStorage.selectedCustomer, pid);
      } else
         pid = sessionStorage.getItem("selectedProject" + sessionStorage.selectedCustomer);
      if (sessionStorage.getItem("selectedTask" + pid) == null)
         sessionStorage.setItem("selectedTask" + pid, <?php echo ($lastTask); ?>);
   </script>

</head>

<body>

   <?php


   //Loading time data according to filter(or not)
   $sid = $_SESSION['userid'];
   //Makeing sure there is only 1 filter present at a time and task-filter has priority(because task filter is always project-specific)
   $isPFilter = isset($_GET['project_filter']);
   $isTFilter = isset($_GET['task_filter']);
   $sql = "SELECT t.start AS start, t.stop AS stop, p.name AS project, ta.name AS task, t.text AS text FROM time t INNER JOIN task ta ON t.task_id = ta.id INNER JOIN project p ON ta.project_id = p.id WHERE t.user_id = ? and t.billdate is null"
      . ($isTFilter ? " and ta.id = ?" : ($isPFilter ? " and ta.project_id = ?" : "")) . " order by t.start";
   $filter_id = $isTFilter ? $_GET['task_filter'] : ($isPFilter ? $_GET['project_filter'] : 0);
   $result = ($isPFilter || $isTFilter) ? get_db_result($db, $sql, "ii", $sid, $filter_id) : get_db_result($db, $sql, "i", $sid);
   if (!$result) {
      echo ("Statment failed: (" . $db->errno . ") " . $db->error);
      die($sql);
   }

   $rowcnt = mysqli_num_rows($result);
   //Bill-Time and User-Manager links
   if ($_SESSION['userlevel'] >= LEVEL_EDIT_USER || $_SESSION['userlevel'] >= LEVEL_CREATE_USER)
      printf("<a href='user_list.php' class='tooltip'><img src='icons/22/im-user.png'><div class='rtooltiptext'>%s</div></a>", RLang("usermngr"));
   if ($_SESSION['userlevel'] >= LEVEL_BILL)
      printf("<a href='bill_time.php' class='tooltip'><img src='icons/22/help-donate.png'><div class='rtooltiptext'>%s</div></a>", RLang("billtime"));
   ?>
   <a href='logout.php' class='tooltip'><img src='icons/22/edit-undo.png'>
      <div class='rtooltiptext'><?php ELang("logout"); ?></div>
   </a>
   <div align="center">
      <h3> <?php printf("%s %s", RLang("hello"), $_SESSION['username']); ?></h3>
      <h4><?php ELang("billabletime"); ?> <?php # echo($rowcnt); 
                                          ?></h4>
      <?php if ($isPFilter) echo ("<a class='tooltip' href:'maintime.php'><img src='icons/22/dialog-cancel.png'><div class='rtooltiptext'>Filter zurücksetzten</div></a>"); ?>
      <table cellspacing="0" cellpadding="0" border="0" width="100%">
         <tr>
            <td>
               <table id="main_table" class="DataTable">
                  <col width="180">
                  <col width="180">
                  <col width="150">
                  <col width="150">
                  <col width="auto">
                  <col width="50">
                  <tr>
                     <th><?php ELang("start"); ?></th>
                     <th><?php ELang("stop"); ?></th>
                     <th><?php ELang("project"); ?></th>
                     <th><?php ELang("task"); ?></th>
                     <th><?php ELang("text"); ?></th>
                     <th><?php ELang("hrs"); ?></th>
                  </tr>
               </table>
            </td>
         </tr>
         <tr>
            <td>
               <div class="Scrollable" style="height:<?php if ($_SESSION['sheight'] == 0) echo ("300");
                                                      else echo ($_SESSION['sheight'] / 100 * 33); ?>px">
                  <table id="main_table" class="DataTable">
                     <col width="180">
                     <col width="180">
                     <col width="150">
                     <col width="150">
                     <col width="auto">
                     <col width="50">
                     <?php
                     for ($i = 0; $i < $rowcnt; $i++) {
                        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
                        $hrs = get_hour_diff_from_sql_datetime($row['start'], $row['stop']);
                        if (!$hrs) {
                           //Should never happen since we already check this at record time, but you never know if some1 does evil vodoo with the DB
                           $_SESSION['msgtype'] = "error";
                           $_SESSION['msg'] = "Fehler: Start-Zeit ist nach oder gleich Stop-Zeit. Auswertung fehlgeschlagen. ID=" . $row['id'];
                           header("Location: maintime.php");
                           exit();
                        }
                        printf("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", $row['start'], $row['stop'], $row['project'], $row['task'], $row['text'], $hrs);
                     }
                     mysqli_free_result($result);
                     ?>

                  </table>
               </div>
            </td>
         </tr>
      </table>
      <!-- Record Time section -->
      <h4><?php ELang("recordworktime"); ?>: </h4>
      <div alignment="horizontal">
         <form method="post" action="record_time.php" autocomplete="off">
            <table class="InputTable">
               <tr>
                  <th><?php ELang("startdate"); ?></th>
                  <th><?php ELang("starttime"); ?></th>
                  <th><?php ELang("enddate"); ?></th>
                  <th><?php ELang("endtime"); ?></th>
                  <th><?php ELang("activity"); ?></th>
               </tr>
               <tr>
                  <td>
                     <input type="text" class="datepicker" name="startdate" id="startdate" />
                  </td>
                  <td>
                     <input type="text" name="starttime" />
                  </td>
                  <td>
                     <input type="text" class="datepicker" name="stopdate" />
                  </td>
                  <td>
                     <input type="text" name="stoptime" />
                  </td>
                  <td>
                     <input type="text" name="text" />
                  </td>
               </tr>
            </table>
            <script type="text/javascript">
               //Init Date-Picker
               datepicker.create('.datepicker', {
                  firstDayOfWeek: 1,
                  months: {
                     short: [<?php ELang("datepicker_months_short"); ?>],
                     long: [<?php ELang("datepicker_months_long"); ?>]
                  },
                  weekdays: {
                     short: [<?php ELang("datepicker_weekdays_short"); ?>],
                     long: [<?php ELang("datepicker_weekdays_long"); ?>]
                  },
                  outputFormat: '%Y-%m-%d'
               });
            </script>
            <div class="SubTableBar" alignment="horizontal">
               <!-- Customer block -->
               <?php
               $lvl_links  =
                  [
                     "edit" => ["link" => "edit_customer.php", "level" => LEVEL_EDIT_CUSTOMER],
                     "retire" => ["link" => "retire_customer.php", "level" => LEVEL_RETIRE_CUSTOMER],
                     "create" => ["link" => "edit_customer.php", "level" => LEVEL_CREATE_CUSTOMER],
                     "unretire" => ["link" => "unretire_customer.php", "level" => LEVEL_UNRETIRE_CUSTOMER]

                  ];
                  //parent_id should be null and $last_parent = -1 in case there is no remote field
               CreateSubListBlock($db, "resource-group.png", RLang("customer"), RLang("customers"), "c", "customer", $lastcustomer, -1, null, "CustomerGroup", $lvl_links, "selectCustomer", null);
               ?>
              
               <!-- Project block -->
               <?php
               $lvl_links  =
                  [
                     "edit" => ["link" => "edit_project.php", "level" => LEVEL_EDIT_PROJECT],
                     "retire" => ["link" => "retire_project.php", "level" => LEVEL_RETIRE_PROJECT],
                     "create" => ["link" => "edit_project.php", "level" => LEVEL_CREATE_PROJECT],
                     "unretire" => ["link" => "unretire_project.php", "level" => LEVEL_UNRETIRE_PROJECT]

                  ];
               CreateSubListBlock($db, "mail-mark-task.png", RLang("project"), RLang("projects"), "p", "project",$lastProject, $lastcustomer, "customer_id", "ProjectGroup", $lvl_links, "selectProject", "project_filter");
               ?>
               <!-- Task block -->
               <?php
               $lvl_links  =
                  [
                     "edit" => ["link" => "edit_task.php", "level" => LEVEL_EDIT_TASK],
                     "retire" => ["link" => "retire_task.php", "level" => LEVEL_RETIRE_TASK],
                     "create" => ["link" => "edit_task.php", "level" => LEVEL_CREATE_TASK],
                     "unretire" => ["link" => "unretire_task.php", "level" => LEVEL_UNRETIRE_TASK]

                  ];
               CreateSubListBlock($db, "mail-mark-task.png", RLang("task"), RLang("tasks"), "t", "task",$lastTask, $lastProject, "project_id", "TaskGroup", $lvl_links, "selectTask", "task_filter");
               ?>
            </div>
            <br />
            <input type="submit" value="<?php ELang("save"); ?>">

         </form>
      </div>
      <!-- Message Output -->
      <p>
         <?php printMSG(); ?>
      </p>
      <script type="text/javascript">
         //Init Time pickers
         window.picker1 = new JsTimepicker(document.querySelector('[name="starttime"]'), {
            hourLeadingZero: true,
            minuteLeadingZero: true
         });
         window.picker2 = new JsTimepicker(document.querySelector('[name="stoptime"]'), {
            hourLeadingZero: true,
            minuteLeadingZero: true
         });
         var project_groups = document.getElementsByClassName("ProjectGroup");

         function setProjectVisible(cid) {
            //Hide all projects
            for (var i = 0; i < project_groups.length; i++) {
               project_groups[i].style.display = "none";
            }
            //find selected and make visible
            var pg = document.getElementById("pg" + cid);
            if (pg)
               pg.style.display = "table";
            //Ensure selection(and sub selections)
            var pid = sessionStorage.getItem("selectedProject" + cid);
            if (pid != null) {
               el = document.getElementById("p" + pid);
               el.checked = true;
               setTaskVisible(pid);
            } else {
               setTaskVisible(-1);
            }
         }

         var task_groups = document.getElementsByClassName("TaskGroup");

         function setTaskVisible(pid) {
            //Hide all tasks
            for (var i = 0; i < task_groups.length; i++) {
               task_groups[i].style.display = "none";
            }
            //Find selected one and make visible
            var tg = document.getElementById("tg" + pid);
            if (tg)
               tg.style.display = "table";
            //Ensure Task Selection(radio button)
            var tid = sessionStorage.getItem("selectedTask" + pid);
            if (tid != null) {
               el = document.getElementById("t" + tid);
               el.checked = true;
            }
         }

         //Saves Project ID in session
         function selectTask(tid) {
            pid = sessionStorage.getItem("selectedProject" + sessionStorage.selectedCustomer);
            sessionStorage.setItem("selectedTask" + pid, tid);
         }

         //Saves Project ID in session and makes corresponding Tasks visible(and selected)
         function selectProject(pid) {
            sessionStorage.setItem("selectedProject" + sessionStorage.selectedCustomer, pid);
            setTaskVisible(pid);
         }
         //Saves Customer ID in session and makes corresponding Projects visible(and selected)
         function selectCustomer(cid) {
            sessionStorage.selectedCustomer = cid;
            setProjectVisible(cid);
         }

         //Ensure visibility and radio-button selection of last-selected Project->Task
         if (sessionStorage.selectedCustomer != null) {
            el = document.getElementById("c" + sessionStorage.selectedCustomer);
            el.checked = true;
            setProjectVisible(sessionStorage.selectedCustomer);
         }
      </script>


</body>

</html>